package cn.q3c.parse.stock2.impl;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import cn.q3c.parse.base.BaseParse;
import cn.q3c.parse.stock2.object.StockInfo;
import cn.q3c.parse.stock2.commons.StockUtils;
import cn.q3c.parse.stock2.object.StockTradeLog;
import cn.q3c.parse.stock2.service.StockServiceImpl;

/**
 * 股票交易数据解析
 * 
 * @author wangxinning
 * 
 */
public class Stock2ParseImpl implements BaseParse {

	public static StockServiceImpl stockService = new StockServiceImpl();

	private static final Logger logger = Logger
			.getLogger(Stock2ParseImpl.class);

	public Object parse(String url, File file) {

		try {
			Date tradeDate = getTradeDate(url);// 交易日期
			String stockCode = getStockCode(url);// 股票代码
			int sctype = getSctype(url);// 交易所

			logger.debug("  交易日期：" + tradeDate);
			logger.debug("  stockCode：" + stockCode);
			logger.debug("  sctype：" + sctype);

			int stockid = stockService.stockCodeToSystemStockID(sctype,
					stockCode);

			logger.debug("  系统分配股票代码stockid：" + stockid);

			//logger.debug("  AAfile=" + file + ",size=" + FileUtils.sizeOf(file));
			
			if (stockid > 0 && FileUtils.sizeOf(file) > FileUtils.ONE_KB) {
				
				logger.debug("  file=" + file + ",size=" + FileUtils.sizeOf(file));
				
				List<StockTradeLog> stockTradeLogList = StockUtils
						.toStockTradeLogList(stockid, tradeDate, file);// 文件转换为对象列表

				logger.debug("  解析成功：交易笔数=" + stockTradeLogList!=null?stockTradeLogList.size():0);
				return stockTradeLogList;
//				logger.debug("  解析交易数据列表：" + stockTradeLogList.size());
//
//				// 处理日志列表（一只股票一天的交易数据）
//				if (!ObjectUtils.isEmptyList(stockTradeLogList)) {
//					stockService.processTradeOneDay(stockTradeLogList);
//				}
			}

		} catch (Exception e) {
			logger.error("行情解析异常,url=" + url + ",file=" + file, e);
		}

		return null;
	}

	private Date getTradeDate(String url) throws ParseException {

		// http://market.finance.sina.com.cn/downxls.php?date=2013-07-09&symbol=sh600717
		String dateStr = StringUtils.substringBetween(url, "date=", "&");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.parse(dateStr);
	}

	private String getStockCode(String url) {
		String longCode = StringUtils.substringAfter(url, "symbol=");
		return StringUtils.substring(longCode, 2);
	}

	private int getSctype(String url) {
		String longCode = StringUtils.trimToEmpty(StringUtils.substringAfter(
				url, "symbol="));
		int sctype = StringUtils.startsWith(longCode, "sh") ? StockInfo.SC_SHANGHAI
				: StockInfo.SC_SHENZHEN;
		return sctype;
	}
}